package com.example.litterpainterdemo.draw.color

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.litterpainterdemo.databinding.LayoutColorItemBinding
import com.example.litterpainterdemo.draw.view.DrawViewModel

class ColorAdapter:RecyclerView.Adapter<ColorAdapter.ColorHolder>() {
    private lateinit var binding: LayoutColorItemBinding
    var colors:List<ColorModel> = emptyList()
    private var lastColorContainer = -1 //记录上一次颜色
    var viewModel: DrawViewModel? = null
    private var isFirst = true

    @SuppressLint("NotifyDataSetChanged")
    fun setData(colorList:List<ColorModel>){
        colors = colorList
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ColorHolder {
        val inflater = LayoutInflater.from(parent.context)
        binding = LayoutColorItemBinding.inflate(inflater,parent,false)
        return ColorHolder(binding)
    }

    override fun getItemCount(): Int {
        return colors.size
    }

    override fun onBindViewHolder(holder: ColorHolder, position: Int) {
        holder.bind(colors[position])
    }


    inner class ColorHolder(private val binding:LayoutColorItemBinding):RecyclerView.ViewHolder(binding.root){
        fun bind(model: ColorModel){
            binding.colorContainer.setBackgroundColor(model.color)

            //进入画板，默认选中的是第一个
            if(isFirst) {
                colors.first().also {
                    it.isSelect = true
                    lastColorContainer = colors.indexOf(it)
                    //将颜色传出去
                    viewModel?.let { viewModel ->
                        viewModel._color.postValue(it.color)
                    }
                    isFirst = false
                }
            }

            binding.strokeView.visibility = if(model.isSelect) View.VISIBLE else View.INVISIBLE

            //添加点击事件
            binding.colorContainer.setOnClickListener {
                binding.strokeView.visibility = View.VISIBLE
                val index = colors.indexOf(model)
                if(lastColorContainer == -1){ //第一次
                    lastColorContainer = index
                    model.isSelect = true
                    notifyItemChanged(lastColorContainer)
                }else{
                    //取消上一次的选中
                    colors[lastColorContainer].isSelect = false
                    notifyItemChanged(lastColorContainer)
                    lastColorContainer = index
                    colors[index].isSelect = true
                    notifyItemChanged(index)
                }

                //将颜色传出去
                viewModel?.let {
                    it.setColor(model.color)
                }
            }
        }
    }
}